package com.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.apache.log4j.Logger;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.jsf.FacesContextUtils;

import com.builder.MarcaBuilder;
import com.dao.BaseModelDAO;
import com.model.Marca;
import com.query.MarcaQuery;
import com.util.JSFUtil;
import com.view.MarcaView;

@ManagedBean
@ViewScoped
@SuppressWarnings("serial")
public class MarcaController extends PaginableController<Marca> {

	private Logger log = Logger.getLogger(MarcaController.class);
	private BaseModelDAO<Marca> dao;
	private Marca marca;
	private MarcaQuery marcaQuery;

	@ManagedProperty("#{marcaView}")
	private MarcaView marcaView;

	@ManagedProperty("#{marcaBuilder}")
	private MarcaBuilder marcaBuilder;

	@SuppressWarnings("unchecked")
	public MarcaController() {
		try {
			dao = (BaseModelDAO<Marca>) FacesContextUtils
					.getWebApplicationContext(FacesContext.getCurrentInstance())
					.getBean("marcaDAO");
			marcaQuery = new MarcaQuery();
			addEdit = false;

		} catch (Throwable e) {
			log.error("Error al inicializar la clase MarcaController", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}


	public void query(ActionEvent event) {
		loadList();
	}

	public void edit(ActionEvent event) {
		try {
			marca = (Marca) lazyDM.getRowData();
			marca = dao.findFULL(marca.getID());
			marcaView = marcaBuilder.toView(marca);
			addEdit = true;
			
		} catch (Throwable e) {
			log.error("Error al editar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public void delete(ActionEvent event) {
		try {
			marca = (Marca) lazyDM.getRowData();
			dao.delete(marca);
			loadList();
		} catch (Throwable e) {
			log.error("Error al eliminar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public void add(ActionEvent event) {
		addEdit = true;
		clear();
	}

	public void save(ActionEvent event) {
		try {
			marca = marcaBuilder.toDomain(marcaView);

			if (marca.getID() != null) {
				dao.edit(marca);
				addEdit = false;
			} else {
				dao.save(marca);
			}
			clear();
			JSFUtil.saveMessage("Elemento guardado con exito",
					FacesMessage.SEVERITY_INFO);
			if (!addEdit) {
				loadList();
			}
		} catch (DataIntegrityViolationException e) {
			JSFUtil.saveMessage(
					"Error al guardar: La descripcion debe ser unica en el sistema.",
					FacesMessage.SEVERITY_ERROR);
		} catch (Throwable e) {
			log.error("Error al guardar", e);
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Error al realizar la operacion", ""));
		}
	}

	public void cancel(ActionEvent event) {
		addEdit = false;
		lazyDM = null;
	}

	public void clear() {
		marca = new Marca();
		marcaView = new MarcaView();
	}

	private void loadList() {

		lazyDM = new LazyDataModel<Marca>() {
			@Override
			public List<Marca> load(int first, int pageSize,
					String sortField, SortOrder sortOrder,
					Map<String, Object> filters) {

				Map<String, Object> filtro = new HashMap<String, Object>();
				filtro.put("descripcion", marcaQuery.getDescripcion());
				return dao.getList(first, pageSize, "descripcion", true, filtro,
						true);
			}
		};

		Map<String, Object> filtro = new HashMap<String, Object>();
		filtro.put("descripcion", marcaQuery.getDescripcion());
		lazyDM.setRowCount(dao.count(filtro, true).intValue());
	}


	public BaseModelDAO<Marca> getDao() {
		return dao;
	}


	public void setDao(BaseModelDAO<Marca> dao) {
		this.dao = dao;
	}


	public Marca getMarca() {
		return marca;
	}


	public void setMarca(Marca marca) {
		this.marca = marca;
	}


	public MarcaQuery getMarcaQuery() {
		return marcaQuery;
	}


	public void setMarcaQuery(MarcaQuery marcaQuery) {
		this.marcaQuery = marcaQuery;
	}


	public MarcaView getMarcaView() {
		return marcaView;
	}


	public void setMarcaView(MarcaView marcaView) {
		this.marcaView = marcaView;
	}


	public MarcaBuilder getMarcaBuilder() {
		return marcaBuilder;
	}


	public void setMarcaBuilder(MarcaBuilder marcaBuilder) {
		this.marcaBuilder = marcaBuilder;
	}

}
